import { Menu } from 'antd';
import { menuList } from '../router/page';
import { useNavigate, useLocation } from 'react-router-dom'
import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'

const MyMenu = (props) => {
    const navigate = useNavigate()

    let { auth } = props.userInfo; 

    const [newMenu, setNewMenu] = useState([])

    const location = useLocation();
    const [defaultKey, setDefaultKey] = useState('')

    useEffect(() => {
        // 获取当前的路由路径  让默认菜单高亮
        setDefaultKey(location.pathname)

        // 过滤菜单 将redux中的权限字符串转化成数组
        auth = auth.split(',')
        
        // 将没有权限的菜单过滤掉
        const filterAuth = menuList.filter(item => {
            return auth.indexOf(item.auth) !== -1
        })
        
        // 过滤之后的菜单
        setNewMenu(filterAuth)
        
    }, [])

    const handleClick = (data) => {
        // 改变menu选中样式
        setDefaultKey(data.key)
        // 跳转页面
        navigate(data.key)
    }

    return <div className="menu-box">
        <Menu
            onClick={handleClick}
            style={{ width: "100%" }}
            selectedKeys={[defaultKey]} // 默认选中的菜单
            mode="inline"
        >
            {
                newMenu.length && newMenu.map((item) => {
                    return <Menu.Item key={item.path}>
                        {item.title}
                    </Menu.Item>
                })
            }

        </Menu>
    </div>

}

const mapStateToProps = state => state

export default connect(mapStateToProps)(MyMenu)